package com.example.qihuibao.network

import com.example.qihuibao.utils.extension.genericType
import com.google.gson.Gson
import okhttp3.MediaType
import okhttp3.RequestBody
import okhttp3.ResponseBody
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.lang.Exception
import java.util.*

/**
 *     author : cwwei
 *     e-mail : 494545699@qq.com
 *     date   : 2022/08/18
 *     desc   : 封装retrofit统一请求
 */
object RetrofitModel {
    /**
     * post请求
     * url：除baseurl外的url，例如/app/xxx/。。。
     * json：JSONObject
     * result：请求的结果
     */
    inline fun <reified T>postJson(url:String, json: JSONObject, result: Result<T>) {
        val body = RequestBody.create(MediaType.parse("application/json"), json.toString())
        RetrofitManager.getInstance().httpApi.postJson(url, body)?.enqueue(object : Callback<ResponseBody>{
            override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                reqSuccess(response, result)
            }

            override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                reqFailed(t, result)
            }
        })
    }

    /**
     * post请求
     * url：除baseurl外的url，例如/app/xxx/。。。
     * json：JSONObject(数据经过RSA加密)
     * result：请求的结果
     */
//    inline fun <reified T>postJson2(url:String, body: RequestBody, result: Result<T>) {
//        api.postJson2(Config.appCode, System.currentTimeMillis().toString(), url, body)?.enqueue(object : Callback<ResponseBody>{
//            override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
//                reqSuccess(response, result)
//            }
//
//            override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
//                reqFailed(t, result)
//            }
//        })
//    }

    /**
     * post请求
     * url：除baseurl外的url，例如/app/xxx/。。。
     * json：JSONObject(数据经过RSA加密)
     * result：请求的结果
     */
//    inline fun <reified T>postJson2NoRSA(url:String, json: JSONObject, result: Result<T>) {
//        val body = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), json.toString())
//        api.postJson2(Config.appCode, System.currentTimeMillis().toString(), url, body)?.enqueue(object : Callback<ResponseBody>{
//            override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
//                reqSuccess(response, result)
//            }
//
//            override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
//                reqFailed(t, result)
//            }
//        })
//    }

    /**
     * post请求
     * url：除baseurl外的url，例如/app/xxx/。。。
     * form：Map<String,String>
     * result：请求的结果
     */
    inline fun <reified T>postForm(url:String, form:SortedMap<String,Any>, result: Result<T>) {
        RetrofitManager.getInstance().httpApi.postForm(url, form)?.enqueue(object : Callback<ResponseBody>{
            override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                reqSuccess(response, result)
            }

            override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                reqFailed(t, result)
            }
        })
    }

    inline fun <reified T> reqSuccess(response: Response<ResponseBody>, result: Result<T>) {
        var data = response.body()?.string()?:"数据异常"
        if (data.contains("\\\"")) {//返回的json格式有问题时
            data = data.replace("\\\"", "\"").replace("\"{", "{").replace("}\"", "}");
        }
        try {
            result.onSucced(parse<T>(data))
        }catch (e:Exception) {
            result.onFailed(data)
        }
    }

    fun <T> reqFailed(t: Throwable, result: Result<T>) {
        var errorMsg = t.message?:"请求异常"
        when {
            errorMsg.toLowerCase(Locale.ROOT).contains("no address associated with hostname") -> errorMsg = "请检查网络"
            errorMsg.toLowerCase(Locale.ROOT).contains("failed to connect") -> errorMsg = "网络/服务器异常"
            errorMsg.toLowerCase(Locale.ROOT).contains("timeout") -> errorMsg = "请求超时"
        }
        result.onFailed(errorMsg)
    }

    //使用内联函数可以把json数据转换为某个类实例
//    inline fun <reified T>parse(data: String):T = Gson().fromJson(data, T::class.java)
    inline fun <reified T>parse(data: String):T = Gson().fromJson(data, genericType<T>())

    //结果回调
    interface Result<T> {
        fun onSucced(result: T)
        fun onFailed(errMsg: String)
    }

}
